//
//  CarShipViewController.m
//  EasyToo
//
//  Created by linshengqin on 13-9-1.
//
//

#import "CarShipViewController.h"
#import "TotalTaxCtlViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DeviceUtil.h"
#import "CarShipTaxCalculate.h"
@interface CarShipViewController ()

@end

@implementation CarShipViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    datamodel = [ConfirmDataModel shareData];
	// Do any additional setup after loading the view.
 //   self.view.backgroundColor = [UIColor whiteColor];
         [self.view setBackgroundColor:BackgroundColor];
    [self.navigationItem setTitle:@"车船税"];

    CarOutputArray = [[NSMutableArray alloc]initWithObjects:@"123",@"2",@"3",@"4",@"5",@"6",@"7",@"8", nil];
    [self initMainView];
    [self createBusNumberTextfiled];
    [self createBusOutputButton] ;
    [self createBusLastTimeBuyButton] ;
    [self createTipsLabel];
    [self createNextButton];
    [self createWarmTipsLabel];
}
-(void)initMainView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight])];
    [self.view addSubview:_bgScrollView];
    _bgScrollView.contentSize = CGSizeMake(320, 700);
    _bgScrollView.showsVerticalScrollIndicator = YES;

}
-(void)createBusNumberTextfiled
{
    BusNumberTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, [DeviceUtil getScreenWidth]-20, 50)];
    BusNumberTextfiled.placeholder= @"车牌号码 粤A" ;
    BusNumberTextfiled.font = [UIFont fontWithName:@"Arial" size:18.0f];
    BusNumberTextfiled.textColor = [UIColor blackColor];

    BusNumberTextfiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    BusNumberTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    BusNumberTextfiled.delegate = self ;
    BusNumberTextfiled.returnKeyType =UIReturnKeyDone;
    BusNumberTextfiled.layer.borderColor = [UIColor grayColor].CGColor;
    BusNumberTextfiled.layer.borderWidth = 1 ;
    BusNumberTextfiled.layer.cornerRadius = 10 ;
    
    [_bgScrollView addSubview:BusNumberTextfiled];
    [BusNumberTextfiled release];
}
-(void)createBusOutputButton
{
//    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 120, 300, 50)];
  //  [btn setBackgroundImage:[UIImage imageNamed:@"button_4.png"] forState:UIControlStateNormal];
    outPutTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(10, 70, [DeviceUtil getScreenWidth]-20, 50)];
    outPutTextfiled.placeholder= @"车辆排量" ;
    outPutTextfiled.font = [UIFont fontWithName:@"Arial" size:18.0f];
    outPutTextfiled.textColor = [UIColor blackColor];
    outPutTextfiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    outPutTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    outPutTextfiled.delegate = self ;
    outPutTextfiled.returnKeyType =UIReturnKeyDone;
    outPutTextfiled.layer.borderColor = [UIColor grayColor].CGColor;
    outPutTextfiled.layer.borderWidth = 1 ;
    outPutTextfiled.layer.cornerRadius = 10 ;
    outPutTextfiled.tag = 100;
    
    // 建立 UIToolbar
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], 44)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelPicker)];
    // 把按鈕加進 UIToolbar
    toolBar.items = [NSArray arrayWithObject:right];
    outPutTextfiled.inputAccessoryView = toolBar;
    
    outPutArray = [[NSArray arrayWithObjects:@"1.0升(含)以下的",@"1.0升以上至1.6升(含)的",@"1.6升以上至2.0升(含)的",@"2.0升以上至2.5升(含)的",@"2.5升以上至3.0升(含)的",@"3.0升以上至4.0升(含)的",@"4.0升以上的",  nil] retain];
    outPutSelectPicker = [[[UIPickerView alloc]initWithFrame:CGRectZero]autorelease];
    outPutSelectPicker.showsSelectionIndicator = YES;
    outPutSelectPicker.frame = CGRectMake(0, 100, 0, 0);
    outPutSelectPicker.tag = 300;
    
    outPutTextfiled.inputAccessoryView = toolBar;
    outPutTextfiled.delegate = self;
    outPutSelectPicker.delegate = self;
    outPutSelectPicker.dataSource = self;
    outPutSelectPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    outPutTextfiled.inputView = outPutSelectPicker;
    
    [_bgScrollView addSubview:outPutTextfiled];
}

-(void)createBusLastTimeBuyButton
{
    
    lastTimeTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(10, 130, [DeviceUtil getScreenWidth]-20, 50)];
    lastTimeTextfiled.placeholder= @"最后购买年份" ;
    lastTimeTextfiled.font = [UIFont fontWithName:@"Arial" size:18.0f];
    lastTimeTextfiled.textColor = [UIColor blackColor];
    lastTimeTextfiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    lastTimeTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    lastTimeTextfiled.delegate = self ;
    lastTimeTextfiled.returnKeyType =UIReturnKeyDone;
    lastTimeTextfiled.layer.borderColor = [UIColor grayColor].CGColor;
    lastTimeTextfiled.layer.borderWidth = 1 ;
    lastTimeTextfiled.layer.cornerRadius = 10 ;

    [_bgScrollView addSubview:lastTimeTextfiled];

    
}
-(void)createTipsLabel
{
    UILabel *tipslabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 190, [DeviceUtil getScreenWidth]-20, 30)];
    tipslabel.text = @"必须购买过以前的车船税,才可以缴交当年的车船税";
    tipslabel.textAlignment = NSTextAlignmentLeft ;
    tipslabel.font = [UIFont fontWithName:@"Arial" size:13.0f];
    tipslabel.textColor = [UIColor grayColor];
    [tipslabel setBackgroundColor:[UIColor clearColor]];

    [_bgScrollView addSubview:tipslabel];
    [tipslabel release];
}
-(void)createNextButton
{
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(10, 220, [DeviceUtil getScreenWidth]-20, 50)];
    [btn setBackgroundImage:[UIImage imageNamed:@"button_3.png"] forState:UIControlStateNormal];
    [btn setTitle:@"下一步" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(nextStep:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius =10 ;
    
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_bgScrollView addSubview:btn];
    [btn release];
    
    
}
-(void)nextStep:(UIButton*)btn
{
    NSLog(@"next step");
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *now = [date  dateByAddingTimeInterval: interval];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned units  = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
    NSDateComponents *comp = [myCal components:units fromDate:now];
    int currentYear = [comp year];
    printf("currentyear:%d\n", currentYear);

    
    if( [BusNumberTextfiled.text length] == 0 || [outPutTextfiled.text length] == 0 || lastTimeTextfiled == nil)
    {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"设置未完整" delegate:self.view cancelButtonTitle:@"ok" otherButtonTitles : nil];
        [alertview show] ;
        [alertview release] ;
        
    }
    else if([lastTimeTextfiled.text intValue]<currentYear-6 || [lastTimeTextfiled.text intValue]>currentYear-1)
    {
        NSString *alertTitle = [NSString stringWithFormat:@"请输入%d到%d之间的年份",currentYear-6, currentYear-1];
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:alertTitle delegate:self.view cancelButtonTitle:@"ok" otherButtonTitles : nil];
        [alertview show];
        [alertview release];
    }
    else
    {
        TotalTaxCtlViewController *totalCtl = [[TotalTaxCtlViewController alloc]init];
//        [self presentViewController:totalCtl animated:YES completion:nil];
        [datamodel.CarNumStr setString:BusNumberTextfiled.text] ;
        [datamodel.payWatStr setString:outPutTextfiled.text] ;
        [datamodel.BuyDateStr setString:lastTimeTextfiled.text] ;
        CarShipTaxCalculate *taxCalc = [[CarShipTaxCalculate alloc] initWithLatestPaidYear:[datamodel.BuyDateStr floatValue] andDisplacement:[datamodel.payWatStr floatValue]];
        if(![taxCalc calculateTax])
        {
            //TODO 输入有误或输入了当前年份
            NSLog(@"no need to calc tax\n");
        }
        datamodel.taxByYear = taxCalc.taxByYear;
        NSLog(@"datamodel.CarNumStr :%@",datamodel.CarNumStr) ;
        [self.navigationController pushViewController:totalCtl animated:YES];
    }
}
-(void)createWarmTipsLabel
{
    NSString *textOne = @"温馨提示:";
    NSString *textTwo = @"1.需要提供身份证正方面行驶证正副本,车辆登记证复印件或电子扫描件,交易成功后请用户通过电子方式向easytoo@711piao.com提供上述材料;";
    NSString *textThird = @"2.对于不能通过电子方式提供资料的用户，我司亦可提供上门收取资料服务（仅限大广州地区）;";
    NSString *textFouth = @"3.办理时间：收到车主资料后的15个工作日;" ;
    NSString *textFive = @"4.票据快递费用：8元" ;
    NSString *textSix = @"5.咨询热线：400-1888-711";
    NSArray *textArr = [[NSArray alloc]initWithObjects:textOne,textTwo,textThird,textFouth,textFive,textSix, nil];
    CGRect rectOne = CGRectMake(10, 280, [DeviceUtil getScreenWidth]-20, 15) ;
    CGRect rectTwo = CGRectMake(10, 295, [DeviceUtil getScreenWidth]-20, 45) ;
    CGRect rectThird = CGRectMake(10, 340, [DeviceUtil getScreenWidth]-20, 30) ;
    CGRect rectFouth = CGRectMake(10, 370, [DeviceUtil getScreenWidth]-20, 15) ;
    CGRect rectFive = CGRectMake(10, 385, [DeviceUtil getScreenWidth]-20, 15) ;
    CGRect rectSix = CGRectMake(10, 400 ,[DeviceUtil getScreenWidth]-20, 15) ;
    for(int i = 0 ; i < 6 ;i++)
    {
        UILabel *warmTipslabel = [[UILabel alloc]init];
        warmTipslabel.numberOfLines = 0;
        warmTipslabel.text = [textArr objectAtIndex:i];
        warmTipslabel.font = [UIFont systemFontOfSize:10];
        warmTipslabel.textColor = [UIColor grayColor];
        [warmTipslabel setBackgroundColor:[UIColor clearColor]];

        switch (i) {
            case 0:
                [warmTipslabel setFrame:rectOne] ;
                break;
            case 1:
                [warmTipslabel setFrame:rectTwo] ;
                break;
            case 2:
                [warmTipslabel setFrame:rectThird] ;
                break;
            case 3:
                [warmTipslabel setFrame:rectFouth] ;
                break;
            case 4:
                [warmTipslabel setFrame:rectFive] ;
                break;
            case 5:
                [warmTipslabel setFrame:rectSix] ;
                break;
                
            default:
                break;
        }
        [_bgScrollView addSubview:warmTipslabel];
        [warmTipslabel release];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return  YES ;
}
-(void)busOutputList:(UIButton *)btn
{
    if(CaroutputpickrView == nil)
    {
        CaroutputpickrView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30, [DeviceUtil getScreenWidth], 450 )];
        
    }
    [_bgScrollView addSubview:CaroutputpickrView];
    
    CaroutputpickrView.dataSource = self ;
    CaroutputpickrView.delegate = self ;
    
    
    
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(CaroutputpickrView != nil)
    {
        [CaroutputpickrView removeFromSuperview];
    }
}
#pragma picker delegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(pickerView.tag == 300)
        return [outPutArray count];
    else
        return [lastTimeArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if(pickerView.tag == 300)
    {
        return [outPutArray objectAtIndex:row];
    }
    else
        return [lastTimeArray objectAtIndex:row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[[UILabel alloc] init]autorelease];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        //        pickerLabel.minimumFontSize =100.;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 280 ;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    selectCarOutPutStr = nil ;
    SelectButton = nil;
    [CaroutputpickrView release] ,CaroutputpickrView = nil;
    [super dealloc];
}

-(void) cancelPicker {
    [lastTimeTextfiled endEditing:YES];
    [outPutTextfiled endEditing:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if( textField.tag ==100)
    {
        NSInteger row = [outPutSelectPicker selectedRowInComponent:0];
        outPutTextfiled.text = [outPutArray objectAtIndex:row];

        printf("row is:%d\n",row);
        if( row == 0)
        {
            datamodel.volume = @"1";
        }
        else if( row == 1)
        {
            datamodel.volume = @"1.6";

        }
        else if( row == 2)
        {
            datamodel.volume = @"2.0";

        }
        else if( row == 3)
        {
            datamodel.volume = @"2.5";

        }
        else if( row == 4)
        {
            datamodel.volume = @"3.0";

        }
        else if( row == 5)
        {
            datamodel.volume = @"4.0";

        }
        else if( row == 6)
        {
            datamodel.volume = @"5";

        }
    }
}
@end
